import React, { Component, createRef } from "react";
import { Form, Input, Button, Col, Row, Modal, message } from "antd";
import { withRouter } from "react-router-dom";
// 导入验证码组件
import Captcha from "@/components/Captcha";
// 导入模型
import Model from "@/models/common";
const layout = {
    labelCol: {
        span: 8,
    },
    wrapperCol: {
        span: 16,
    },
};
const tailLayout = {
    wrapperCol: {
        offset: 0,
        span: 24,
    },
};
class MobileLogin extends Component {
    // 构造函数
    constructor(props) {
        super(props);
        // 创建表单需要的ref对象
        this.ref_cpt = createRef();
        // 获取验证码组件的ref
        this.ref_captcha = createRef();
        // 获取手机号
        this.ref_mobile = createRef();
    }
    // 状态的初始化
    state = {
        // 用于验证图形验证码的
        key: "",
        // 存储图形验证码的token，在验证图形验证码成功后才会有token
        token: "",
        // token的过期时间
        expire: 0,
        // 模态窗口是否可见
        isModalVisible: false,
        // 短信发送成功后的reqid
        requestId: "",
        // 倒计时计数器
        count: 60,
        // 做一个按钮的标志，用于标识当时按的状态是为获取短信还是倒计时
        can: true,
    };
    render() {
        return (
            <div>
                <Form
                    {...layout}
                    name="basic"
                    initialValues={{
                        remember: true,
                    }}
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                >
                    <Form.Item
                        label="手机号"
                        name="mobile"
                        rules={[
                            {
                                required: true,
                                message: "请输入手机号！",
                            },
                        ]}
                    >
                        <Input ref={this.ref_mobile} />
                    </Form.Item>

                    <Form.Item label="短信验证码">
                        <Row gutter={8}>
                            <Col span={14}>
                                <Form.Item
                                    name="code"
                                    noStyle
                                    rules={[
                                        {
                                            required: true,
                                            message: "请输入短信验证码！",
                                        },
                                    ]}
                                >
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col span={10}>
                                {/* block：让按钮与父元素宽度一样 */}
                                <Button block onClick={this.getCode}>
                                    {this.state.can ? "获取短信" : this.state.count + "秒后获取"}
                                </Button>
                            </Col>
                        </Row>
                    </Form.Item>

                    <Form.Item {...tailLayout}>
                        <Button type="primary" htmlType="submit" block>
                            登录
                        </Button>
                    </Form.Item>
                </Form>

                {/* 模态窗口用一阶段的话来讲，其就是一个弹出的div，不用非得放在Form组件里面 */}
                <Modal title="验证码" visible={this.state.isModalVisible} onOk={this.handleOk} onCancel={this.handleCancel} okText="确定" cancelText="取消">
                    <Form>
                        <Form.Item label="验证码">
                            <Row gutter={8}>
                                <Col span={14}>
                                    <Form.Item
                                        name="captcha"
                                        noStyle
                                        rules={[
                                            {
                                                required: true,
                                                message: "请输入验证码！",
                                            },
                                        ]}
                                    >
                                        <Input ref={this.ref_cpt} />
                                    </Form.Item>
                                </Col>
                                <Col span={10}>
                                    {/* 放上验证码组件 */}
                                    <Captcha height="31.6" setKey={this.setKey} ref={this.ref_captcha} />
                                </Col>
                            </Row>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    }

    // 整体表单的提交事件
    onFinish = (values) => {
        // console.log("Success:", values);
        // 装载请求短信的id
        values["requestId"] = this.state.requestId;
        // 进行网络请求
        Model.mobileLogin(values).then((ret) => {
            if (ret.errNo === 0) {
                message.success(ret.message, 2, () => {
                    // 跳转到后台首页
                    this.props.history.push("/dashboard");
                });
            } else {
                message.error(ret.errText);
            }
        });
    };

    // 整体表单的错误事件
    onFinishFailed = (errorInfo) => {
        console.log("Failed:", errorInfo);
    };

    // 短信验证码的获取方法
    getCode = () => {
        let mobile = this.ref_mobile.current.props.value;
        if (/^1[3-9]\d{9}$/.test(mobile)) {
            if (this.state.can) {
                // 显示弹窗
                this.showModal(true);
            }
        } else {
            message.error("请输入正确的手机号");
        }
    };

    // 倒计时
    countDown = () => {
        if (this.state.count === 1) {
            this.setState(() => {
                return {
                    count: 60,
                    can: true,
                };
            });
        } else {
            this.setState((state) => {
                return {
                    count: state.count - 1,
                };
            });
            setTimeout(() => {
                this.countDown();
            }, 1000);
        }
    };

    // 控制模态窗口的显示与否
    showModal = (flag) => {
        this.setState(() => {
            return {
                isModalVisible: flag,
            };
        });
    };

    // 模态窗口确定按钮的回调事件
    handleOk = () => {
        // this.showModal(false);
        // 开始验证用户的图形验证码
        let values = {};
        // 装载请求的数据
        let mobile = this.ref_mobile.current.props.value;
        values["captcha"] = this.ref_cpt.current.props.value;
        values["key"] = this.state.key;
        // 发送请求验证图形验证码
        Model.verifyCpt(values).then((ret) => {
            // 判断结果
            if (ret.errNo === 0) {
                message.success(ret.message, 2, () => {
                    // 保存token及expire
                    this.setState(
                        () => {
                            return {
                                token: ret.context.token,
                                expire: ret.context.expire,
                            };
                        },
                        () => {
                            // 关闭窗口
                            this.showModal(false);
                            // 发送验证码
                            // 发送请求
                            let data = {};
                            data["token"] = this.state.token;
                            data["mobile"] = mobile;
                            data["type"] = 0;
                            Model.getCode(data).then((ret) => {
                                if (ret.errNo === 0) {
                                    // 测试倒计时
                                    this.setState(() => {
                                        return { can: false };
                                    });
                                    this.countDown();
                                    // 赋值
                                    message.success(ret.message, 2, () => {
                                        this.setState(() => {
                                            return {
                                                requestId: ret.requestId,
                                            };
                                        });
                                    });
                                } else {
                                    message.error(ret.errText);
                                }
                            });
                        }
                    );
                });
            } else {
                message.error(ret.errText);
                this.ref_captcha.current.loadCaptcha();
            }
        });
    };

    // 模态窗口的取消按钮的回调事件
    handleCancel = () => {
        this.showModal(false);
    };

    setKey = (key) => {
        this.setState(() => {
            return { key };
        });
    };
}

export default withRouter(MobileLogin);
